import { Context } from 'koa'
import { AppDataSource } from '../data-source'

import { User } from '../entity/User'

const userRepo = AppDataSource.getRepository(User)

type CtxQuery = {
  email: string
  name: string
}

export default class UserController {
  public static async listUsers(ctx: Context) {
    const [users, count] = await userRepo.findAndCount({
      // 常用的选项
      relations: {
        userInfo: true,
      },
      // select:{
      //   email:true,
      //   name:true
      // },
      // order:{
      //   id:"ASC"
      // }
      // cache: true,
      // skip: 0,
      // take: 2,
    })

    ctx.body = {
      data: {
        users,
        count,
      },
      msg: '查询成功1',
    }
  }

  public static async showUserById(ctx: Context) {
    const id = ctx.params.id as User['id']
    const user = await userRepo.findOne({
      where: {
        id,
      },
      relations: {
        userInfo: true,
        userGroup: true,
      },
    })

    if (user) {
      ctx.status = 200
      ctx.body = {
        data: user,
        msg: '查询成功',
      }
    } else {
      ctx.status = 404
    }
  }

  public static async showUserDetail(ctx: Context) {
    const { email, name } = ctx.request.body as User

    const users = await userRepo.findBy({ name })

    if (users) {
      ctx.body = {
        data: users,
        msg: '查询成功',
      }
    } else {
      ctx.body = {
        data: {},
        msg: '未查询到',
      }
    }
  }

  public static async updateUser(ctx: Context) {
    const id: number = ctx.params.id
    const { email, name } = <CtxQuery>ctx.request.query
    const oldUser = await userRepo.findOneBy({ id })
    oldUser.name = name
    oldUser.email = email

    const updatedUser = await userRepo.save(oldUser)

    if (updatedUser) {
      ctx.body = {
        data: updatedUser,
        msg: '更新成功',
      }
    } else {
      ctx.body = {
        data: '',
        msg: '更新失败',
      }
    }
  }

  public static async deleteUser(ctx: Context) {
    // 因为我们在UserInfo实体中设置了onDelte属性为CASCADE,属于级联关系，所以
    // 当我们删除user的时候，user附带的userInfo也会删除
    await userRepo.delete(+ctx.params.id)
    ctx.body = {
      data: '',
      msg: '删除成功',
    }
  }
  // 改变用户组
  public static async updateGroup(ctx: Context) {}
}
